#include "login.h"
#include "terminal.h"
#include "uiMessage.h"

using namespace std;
using namespace CTUI;

LoginUI::LoginUI(string addr, int port) 
            : m_length(0)
            , m_startPos(0)
            , m_horizontalBorder('*')
            , m_verticalBorder('*')
{
    setBorderWidth(64);
    loginMainUI();
}

LoginUI::~LoginUI()
{
}

bool LoginUI::handle(const ClientResultMessgae *pMsg)
{
    ResultType t = (ResultType)pMsg->type;
    switch (t)
    {
    case RT_LOGIN:
        if(pMsg->result) {
            cout << "登录成功！\n";
        }
        else {
            cout << "登录失败！\n";
        }
        break;
    case RT_REGISTER:
        break;
    default:
        break;
    }
    std::cout << "> ";
    return true;
}

void LoginUI::run()
{
    while (true)
    {
        std::cout << "> ";
        string str;
        std::cin >> str;
        std::flush(std::cout);
        if(str.empty())
            continue;
        if(str == "1") {
            string user, passwd;
            std::cout << "用户名： ";
            cin >> user;
            std::cout << "密码： ";
            cin >> passwd;

            // 判断用户名密码
            LoginMsg msg;
            msg.user = user;
            msg.passwd = passwd;
            msg.send();
        }
        else if(str == "2") {
            string user, passwd;
            std::cout << "用户名： ";
            cin >> user;
            std::cout << "密码： ";
            cin >> passwd;

            // 判断用户名密码
            RegisterMsg msg;
            msg.user = user;
            msg.passwd = passwd;
            msg.send();
        }
        else if(str == "3") {
            CmdMsg msg;
            msg.cmd = CT_EXIT;
            msg.send();
            exit(0);
        }
        else {
            std::cout << "请输入有效命令！\n ";
        }
    }
}

void LoginUI::loginMainUI()
{
    CLEARSCREEN();
    string space(m_length  - 4, ' ');
    positionPrint(m_startPos, m_borderStyle);
    borderPrint(m_startPos, m_length, m_verticalBorder, space);
    borderCenterPrint(m_startPos, m_length, m_verticalBorder, "欢迎登录在线即时通讯");
    borderPrint(m_startPos, m_length, m_verticalBorder, space);
    borderPrint(m_startPos, m_length, m_verticalBorder, "\t1. 登录");
    borderPrint(m_startPos, m_length, m_verticalBorder, "\t2. 注册");
    borderPrint(m_startPos, m_length, m_verticalBorder, "\t3. 退出");
    borderPrint(m_startPos, m_length, m_verticalBorder, space);
    positionPrint(m_startPos, m_borderStyle);

}

void LoginUI::setBorderWidth(int w)
{
    if (m_length == w)
        return;

    // 1. 赋值长度
    m_length = w;

    // 2. 计算起始位置
    int tm = terminalWidth();
    if (m_length > tm)
    {
        m_length = tm;
        m_startPos = 0;
    }
    else
    {
        m_startPos = (tm - m_length) / 2;
    }

    // 3. 边框字符串
    m_borderStyle.assign(m_length, m_horizontalBorder);
}